package com.adou.shiro.filter;

import com.adou.common.model.User;
import com.adou.common.util.IConfig;
import com.adou.common.util.StringUtil;
import com.adou.common.util.UdpGetClientMacAddr;
import com.adou.common.util.userauth.interfaceUtils;
import com.adou.shiro.token.TokenManager;
import com.adou.shiro.util.ShiroFilterUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class LoginFilter extends AccessControlFilter{

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        User token = TokenManager.getToken();
        if (null != token || isLoginRequest(servletRequest, servletResponse)) {// && isEnabled()
            return Boolean.TRUE;
        }

        Map<String, String> resultMap = new HashMap<>();
        String userid = StringUtil.trimToEmpty(servletRequest.getParameter("userid"));
        String sessionid = StringUtil.trimToEmpty(servletRequest.getParameter("sessionid"));
        String ip = UdpGetClientMacAddr.getIP((HttpServletRequest) servletRequest);

        if (!userid.equals("") || !sessionid.equals("")) {
            JSONObject json = interfaceUtils.getLoginInfoByAuth(IConfig.get("systype"), sessionid, userid,ip,"utf-8");
            if (json == null || json.isEmpty()) {
                if (ShiroFilterUtils.isAjax(servletRequest)) {// ajax请求
                    logger.error("当前用户登陆响应异常，并且是Ajax请求！");
                }
                resultMap.put("result", "700");
                resultMap.put("msg", "当前用户登陆响应异常");//当前用户没有登录或登陆异常！
            } else if (json.getIntValue("result") == 1) {
                JSONObject jdata = json.getJSONObject("data");
                String cuser=java.net.URLDecoder.decode(jdata.getString("cUser"),"utf-8");
                String cusername = "";
                if (jdata.containsKey("cRealname")) {
                    cusername = java.net.URLDecoder.decode(jdata.getString("cRealname") == null ? "" : jdata.getString("cRealname"), "utf-8");
                }
                TokenManager.setVal2Session("id", jdata.getLong("cId"));
                TokenManager.setVal2Session("userid", cuser);
                TokenManager.setVal2Session("username",cusername);
                TokenManager.setVal2Session("sessionid", json.getString("sessionid"));
                Long iAreaid = new Long(0);
                if (jdata.containsKey("iAreaid")) {
                    iAreaid = jdata.getLong("iAreaid");
                }
                TokenManager.setVal2Session("areaid", iAreaid);
                Long iOrgid = new Long(0);
                if (jdata.containsKey("iOrgid")) {
                    iOrgid = jdata.getLong("iOrgid");
                }
                TokenManager.setVal2Session("orgid", iOrgid);
                String cAreaname = "";
                if (jdata.containsKey("cAreaname")) {
                    cAreaname = jdata.getString("cAreaname");
                }
                TokenManager.setVal2Session("areaname", cAreaname);
                String cOrgname = "";
                if (jdata.containsKey("cOrgname")) {
                    cOrgname = jdata.getString("cOrgname");
                }
                TokenManager.setVal2Session("orgname", cOrgname);
                TokenManager.setVal2Session("systype", IConfig.get("systype"));
                return Boolean.TRUE;
            } else {
                if (ShiroFilterUtils.isAjax(servletRequest)) {// ajax请求
                    logger.error(json.getString("msg") + "当前用户信息获取失败，并且是Ajax请求！");
                }
                resultMap.put("result", "701");
                resultMap.put("msg", "当前用户信息获取失败");//当前用户没有登录或登陆异常！
            }
        } else {
            if (ShiroFilterUtils.isAjax(servletRequest)) {// ajax请求
                logger.error("当前用户会话参数丢失，并且是Ajax请求！");
            }
            resultMap.put("result", "702");
            resultMap.put("msg", "当前用户会话参数丢失");//当前用户参数异常！
        }
        ShiroFilterUtils.out(servletResponse, resultMap);
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        saveRequestAndRedirectToLogin(servletRequest, servletResponse);
        Subject subject = getSubject(servletRequest, servletResponse);
        subject.logout();
        return Boolean.FALSE;
    }

}
